package com.zwh.common.easyexcel.converters;

import java.text.NumberFormat;

import com.alibaba.excel.metadata.data.WriteCellData;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;

/**
 * 数值型 <-> String 类型转换器
 * @author monkey
 * @date 2021/3/25 11:14
 **/
public class NumberToStringConvert implements Converter<Number> {
    /**
     * 支持转换的java类
     * @return
     */
    @Override
    public Class supportJavaTypeKey() {
        return Number.class;
    }

    /**
     * 支持的excel类型，读取时候使用
     * @return
     */
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    @Override
    public Number convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if(StringUtils.isBlank(cellData.getStringValue())) {
            return null;
        }
        return NumberFormat.getInstance().parse(cellData.getStringValue());
    }

    @Override
    public WriteCellData convertToExcelData(Number value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return NumberUtils.formatToCellData(value, contentProperty);
    }
}
